<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">付款记录</text>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-tabs">
				<view class="filter-tab" :class="{ active: filterStatus === 'all' }" @click="setFilter('all')">
					<text>全部</text>
				</view>
				<view class="filter-tab" :class="{ active: filterStatus === 'partial' }" @click="setFilter('partial')">
					<text>部分付款</text>
				</view>
				<view class="filter-tab" :class="{ active: filterStatus === 'paid' }" @click="setFilter('paid')">
					<text>已结清</text>
				</view>
			</view>
		</view>

		<!-- 统计信息 -->
		<view class="stats-card">
			<view class="stats-item">
				<text class="stats-label">总付款</text>
				<text class="stats-amount">¥{{ totalPayments.toFixed(2) }}</text>
			</view>
			<view class="stats-item">
				<text class="stats-label">已结清</text>
				<text class="stats-amount success">¥{{ paidAmount.toFixed(2) }}</text>
			</view>
			<view class="stats-item">
				<text class="stats-label">部分付款</text>
				<text class="stats-amount warning">¥{{ partialAmount.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 付款记录列表 -->
		<view class="payments-list" v-if="filteredPayments.length > 0">
			<view v-for="(group, date) in groupedPayments" :key="date" class="date-group">
				<view class="date-header">
					<text class="date-text">{{ formatDate(date) }}</text>
					<text class="date-amount">¥{{ getDateAmount(group).toFixed(2) }}</text>
				</view>
				
				<view v-for="payment in group" :key="payment.id" class="payment-item">
					<view class="payment-left" @click="viewProject(payment)">
						<view class="project-info">
							<text class="project-name">{{ payment.projectName }}</text>
							<text class="payment-time">{{ formatTime(payment.paymentTime) }}</text>
						</view>
						<text class="payment-remark" v-if="payment.remark">{{ payment.remark }}</text>
					</view>
					<view class="payment-right">
						<text class="payment-amount">¥{{ payment.amount.toFixed(2) }}</text>
						<text class="payment-status" :class="payment.status">{{ getStatusText(payment.status) }}</text>
					</view>
					<view class="payment-actions">
						<button class="action-btn edit-btn" @click="editPayment(payment)">编辑</button>
						<button class="action-btn delete-btn" @click="deletePayment(payment)">删除</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<text class="empty-text">暂无付款记录</text>
			<text class="empty-desc">当有项目付款时会显示在这里</text>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			filterStatus: 'all',
			payments: []
		}
	},
	computed: {
		filteredPayments() {
			if (this.filterStatus === 'all') {
				return this.payments
			}
			return this.payments.filter(payment => payment.status === this.filterStatus)
		},
		groupedPayments() {
			const groups = {}
			this.filteredPayments.forEach(payment => {
				const date = payment.paymentTime.split('T')[0]
				if (!groups[date]) {
					groups[date] = []
				}
				groups[date].push(payment)
			})
			return groups
		},
		totalPayments() {
			return this.payments.reduce((sum, payment) => sum + payment.amount, 0)
		},
		paidAmount() {
			return this.payments
				.filter(payment => payment.status === 'paid')
				.reduce((sum, payment) => sum + payment.amount, 0)
		},
		partialAmount() {
			return this.payments
				.filter(payment => payment.status === 'partial')
				.reduce((sum, payment) => sum + payment.amount, 0)
		}
	},
	onShow() {
		this.loadPayments()
	},
	methods: {
		loadPayments() {
			const payments = uni.getStorageSync('project_payments') || []
			this.payments = payments.sort((a, b) => new Date(b.paymentTime) - new Date(a.paymentTime))
		},
		setFilter(status) {
			this.filterStatus = status
		},
		formatDate(dateString) {
			const date = new Date(dateString)
			const today = new Date()
			const yesterday = new Date(today)
			yesterday.setDate(yesterday.getDate() - 1)
			
			if (date.toDateString() === today.toDateString()) {
				return '今天'
			} else if (date.toDateString() === yesterday.toDateString()) {
				return '昨天'
			} else {
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${month}月${day}日`
			}
		},
		formatTime(timeString) {
			const date = new Date(timeString)
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			return `${hours}:${minutes}`
		},
		getDateAmount(payments) {
			return payments.reduce((sum, payment) => sum + payment.amount, 0)
		},
		getStatusText(status) {
			const statusMap = {
				'unpaid': '未付款',
				'partial': '部分付款',
				'paid': '已结清'
			}
			return statusMap[status] || '未知'
		},
		viewProject(payment) {
			uni.navigateTo({
				url: `/pages/project-detail/project-detail?id=${payment.projectId}`
			})
		},
		editPayment(payment) {
			// 获取项目信息以计算剩余应付金额
			const projects = uni.getStorageSync('engineering_projects') || []
			const project = projects.find(p => p.id === payment.projectId)
			
			if (!project) {
				uni.showToast({
					title: '项目不存在',
					icon: 'none'
				})
				return
			}
			
			// 计算已付款总额（不包括当前记录）
			const otherPayments = this.payments.filter(p => 
				p.projectId === payment.projectId && p.id !== payment.id
			)
			const otherPaidAmount = otherPayments.reduce((sum, p) => sum + p.amount, 0)
			const maxAmount = project.totalAmount - otherPaidAmount
			
			uni.showModal({
				title: '编辑付款记录',
				content: '请输入新的付款金额',
				editable: true,
				placeholderText: `最大可输入 ¥${maxAmount.toFixed(2)}`,
				success: (res) => {
					if (res.confirm && res.content) {
						const newAmount = parseFloat(res.content)
						if (isNaN(newAmount) || newAmount <= 0) {
							uni.showToast({
								title: '请输入有效金额',
								icon: 'none'
							})
							return
						}
						
						if (newAmount > maxAmount) {
							uni.showToast({
								title: `金额不能超过 ¥${maxAmount.toFixed(2)}`,
								icon: 'none'
							})
							return
						}
						
						// 更新付款记录
						const payments = uni.getStorageSync('project_payments') || []
						const paymentIndex = payments.findIndex(p => p.id === payment.id)
						
						if (paymentIndex !== -1) {
							payments[paymentIndex].amount = newAmount
							payments[paymentIndex].paymentTime = new Date().toISOString()
							
							// 重新计算项目状态
							const totalPaid = otherPaidAmount + newAmount
							const newStatus = totalPaid >= project.totalAmount ? 'paid' : 'partial'
							payments[paymentIndex].status = newStatus
							
							uni.setStorageSync('project_payments', payments)
							
							// 更新项目状态
							this.updateProjectStatus(project.id, newStatus)
							
							this.loadPayments()
							
							uni.showToast({
								title: '付款记录更新成功',
								icon: 'success'
							})
						}
					}
				}
			})
		},
		deletePayment(payment) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这条付款记录吗？',
				success: (res) => {
					if (res.confirm) {
						// 删除付款记录
						const payments = uni.getStorageSync('project_payments') || []
						const newPayments = payments.filter(p => p.id !== payment.id)
						uni.setStorageSync('project_payments', newPayments)
						
						// 重新计算项目状态
						const projectPayments = newPayments.filter(p => p.projectId === payment.projectId)
						const totalPaid = projectPayments.reduce((sum, p) => sum + p.amount, 0)
						
						const projects = uni.getStorageSync('engineering_projects') || []
						const project = projects.find(p => p.id === payment.projectId)
						
						if (project) {
							const newStatus = totalPaid >= project.totalAmount ? 'paid' : 
											totalPaid > 0 ? 'partial' : 'unpaid'
							this.updateProjectStatus(project.id, newStatus)
						}
						
						this.loadPayments()
						
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
					}
				}
			})
		},
		updateProjectStatus(projectId, status) {
			const projects = uni.getStorageSync('engineering_projects') || []
			const projectIndex = projects.findIndex(p => p.id === projectId)
			
			if (projectIndex !== -1) {
				projects[projectIndex].status = status
				projects[projectIndex].updateTime = new Date().toISOString()
				uni.setStorageSync('engineering_projects', projects)
			}
		}
	}
}
</script>

<style scoped>
.container {
	background: #f5f5f5;
	min-height: 100vh;
	padding: 20rpx;
}

.page-header {
	text-align: center;
	padding: 40rpx 0;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.filter-bar {
	background: white;
	border-radius: 20rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.filter-tabs {
	display: flex;
	background: #f5f5f5;
	border-radius: 15rpx;
	padding: 5rpx;
}

.filter-tab {
	flex: 1;
	text-align: center;
	padding: 20rpx;
	border-radius: 10rpx;
	transition: all 0.3s;
}

.filter-tab.active {
	background: white;
	color: #667eea;
	font-weight: bold;
}

.stats-card {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.stats-item {
	text-align: center;
	flex: 1;
}

.stats-label {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.stats-amount {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.stats-amount.success {
	color: #4CAF50;
}

.stats-amount.warning {
	color: #FF9800;
}

.payments-list {
	margin-bottom: 40rpx;
}

.date-group {
	margin-bottom: 30rpx;
}

.date-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
}

.date-text {
	font-size: 28rpx;
	color: #666;
	font-weight: bold;
}

.date-amount {
	font-size: 28rpx;
	color: #667eea;
	font-weight: bold;
}

.payment-item {
	background: white;
	border-radius: 15rpx;
	padding: 30rpx;
	margin-bottom: 15rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.payment-left {
	flex: 1;
}

.project-info {
	margin-bottom: 10rpx;
}

.project-name {
	font-size: 30rpx;
	color: #333;
	font-weight: bold;
	display: block;
	margin-bottom: 8rpx;
}

.payment-time {
	font-size: 24rpx;
	color: #999;
}

.payment-remark {
	font-size: 24rpx;
	color: #666;
}

.payment-right {
	text-align: right;
	margin-right: 20rpx;
}

.payment-amount {
	font-size: 32rpx;
	font-weight: bold;
	color: #4CAF50;
	display: block;
	margin-bottom: 8rpx;
}

.payment-status {
	padding: 6rpx 12rpx;
	border-radius: 12rpx;
	font-size: 22rpx;
	color: white;
}

.payment-status.unpaid {
	background: #ff4757;
}

.payment-status.partial {
	background: #ffa502;
}

.payment-status.paid {
	background: #2ed573;
}

.payment-actions {
	display: flex;
	gap: 10rpx;
}

.action-btn {
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	font-size: 22rpx;
	border: none;
	color: white;
}

.edit-btn {
	background: #667eea;
}

.delete-btn {
	background: #ff4757;
}

.empty-state {
	text-align: center;
	padding: 100rpx 40rpx;
}

.empty-text {
	font-size: 32rpx;
	color: #999;
	margin-bottom: 20rpx;
	display: block;
}

.empty-desc {
	font-size: 28rpx;
	color: #ccc;
	display: block;
}
</style>
